import React, { useState, useMemo } from 'react'
import { NavBar, Grid } from 'antd-mobile'
import MonthBillList from './Components/MonthBillList'
import { DownOutline } from 'antd-mobile-icons'
import { DatePicker } from 'antd-mobile'
import { useSelector } from 'react-redux'
import _ from 'lodash'
import dayjs from 'dayjs'

const now = new Date()
const Year = () => {
	const billsList = useSelector((state) => state.bills.billsList)
	const [visible, setVisible] = useState(false)
	const [currentYear, setCurrentYear] = useState(new Date().getFullYear())

	const YearGroup = useMemo(() => {
		return _.groupBy(billsList, item => dayjs(item.date).year())
	}, [billsList])

	const [yearBills, setYearBills] = useState(YearGroup[currentYear] || [])

	const yearResult = useMemo(() => {
		const pay = yearBills.filter(item => item.type === 'pay').reduce((acc, cur) => acc + cur.money, 0)
		const income = yearBills.filter(item => item.type === 'income').reduce((acc, cur) => acc + cur.money, 0)
		return {
			pay,
			income,
			total: (income - pay).toFixed(2)
		}
	}, [yearBills])

	return (
		<div style={{ padding: '0 10px' }}>
			<NavBar
				style={{
					'--height': '36px'
				}}
				backIcon={null}

			>
				{currentYear}
				<DownOutline onClick={() => {
					setVisible(true)
				}} />
			</NavBar>
			<DatePicker
				visible={visible}
				max={now}
				onClose={() => {
					setVisible(false)
				}}
				precision='year'
				onConfirm={(date) => {
					setVisible(false)
					const year = date.getFullYear()
					setCurrentYear(year)
					setYearBills(YearGroup[year] || [])
				}}
				cancelText='Cancel'
				confirmText='Confirm'
			/>
			<section>
				<Grid columns={3} >
					<Grid.Item>
						<Grid columns={1} >
							<Grid.Item>
								<span>{yearResult.pay}</span>
							</Grid.Item>
							<Grid.Item>
								<span>pay</span>
							</Grid.Item>
						</Grid>
					</Grid.Item>
					<Grid.Item>
						<Grid columns={1} >
							<Grid.Item>
								<span>{yearResult.income}</span>
							</Grid.Item>
							<Grid.Item>
								<span>income</span>
							</Grid.Item>
						</Grid>
					</Grid.Item>
					<Grid.Item>
						<Grid columns={1} >
							<Grid.Item>
								<span>{yearResult.total}</span>
							</Grid.Item>
							<Grid.Item>
								<span>balances</span>
							</Grid.Item>
						</Grid>
					</Grid.Item>
				</Grid>
			</section>
			<section>
				<MonthBillList billsList={yearBills} />
			</section>
		</div>
	)
}

export default Year